import re

HELPDOC_RE = re.compile("(?:(\\s|^))help(\\[(?P<order>\d+)\\])?\\((?P<helpdoc>(.|\\s)+)(?<!\\\\)\\)")

DEFAULT_ORDER = 100

def gethelp(obj):
    methods = dir(obj)
    helplist = []
    
    for method in methods:
        if method.startswith("_"):
            #Only want 'pubics'
            continue
        
        member = getattr(obj, method)
        if type(member).__name__ != "instancemethod":
            #Only want methods
            continue
        
        helpdocmatch = HELPDOC_RE.search(member.__doc__)
        if helpdocmatch is None:
            continue
        
        helpdoc = helpdocmatch.group("helpdoc")
        helpdoc = helpdoc.strip() #Remove leading/trailing whitespace
        helpdoc = helpdoc.replace("\\(", "(")
        helpdoc = helpdoc.replace("\\)", ")")
        
        order = helpdocmatch.group("order")
        if order is None:
            order = DEFAULT_ORDER
        
        helplist.append((order, method, helpdoc))
    
    if len(helplist) == 0:
        return None
    
    helplist.sort(key=lambda item: item[0])
    
    #The length of the longest method name 
    maxmethodname = len(max(helplist, key=lambda item: len(item[1]))[1])
    
    helpstring = ""
    for helpitem in helplist:
        helpstring +=   "\n" + \
                        helpitem[1] + \
                        " "*(maxmethodname - len(helpitem[1])) + \
                        " - " + \
                        helpitem[2] 
    
    return helpstring